import { Component, OnInit, Input, Output, ViewChild, ChangeDetectionStrategy, OnChanges } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Observable }             from 'rxjs/Observable';
import { Subscription }           from 'rxjs/Subscription';
import 'rxjs/add/operator/take';
// import ngx-bootstrap modal realationship
import { BsModalService }   from 'ngx-bootstrap/modal';
import { BsModalRef }       from 'ngx-bootstrap/modal/modal-options.class';
// import add dialog modify Component
import { ModifyComponent }  from './../modify/modify.component';
import { ConfirmComponent } from './../confirm/confirm.component';
import { AddProductModalDailogComponent } from './../modal-dailog/add-product-modal-dailog.component';
// import product service
import { ProductService }  from './../../core/services/product.service';
import { ProductListPage } from './../../core/class/product-list-page';
import { STATUS }          from './../../core/class/status';


@Component({
    selector: 'product-list',
    templateUrl: './product-list.html',
    styleUrls: ['./product-list.css']
})
export class ProductListComponent implements OnInit {

    status: STATUS[] = [
      {status: 'Alert'},
      {status: 'Normal'},
      {status: 'Archieve'},
      {status: 'Processing'}
    ];

    public modalRef: BsModalRef;
     // pagination
    p:           number = 1; // pagination index
    total:       number;
    productList: any[] = [];
    productId:   number;
    // search sort pagination variable
    key:          string = 'name';
    reverse:      boolean = false;
    errorMessage: string;
    // mock server function variable
    routeSubs: Subscription;
    actionsSubscription: Subscription;
    searchParams: any;
    start:     number;
    end:       number;
    totalPage: number;
    sortField: any;
    order:     string;
    // selector component variable
    statusValue: any;
    tagsValue:   any;
    datesValue:  any;
    pageCount:   number = 5;

    constructor(
      private bsModalService: BsModalService,
      private productService: ProductService,
      private route:          ActivatedRoute,
      private router:         Router
    ) { }

    ngOnInit() {
      // this.getPagePro(1);
      this.generatorGetPage(1);
    }

    getProductDetail() {
      this.router.navigate(['/product-detail'], {queryParams: { asin: 'asin'}});
    }

    getPagePro(page: number) {
      const start = (page - 1) * this.pageCount;
      const end = start + this.pageCount;
      this.productService.pagiFieldPro(start,end, this.statusValue).subscribe(
        data => {
          this.productList = data;
          for (let i = 0; i < this.productList.length; i++) {
            this.productList[i]['checked'] = false;
            console.log(this.productList[i]['checked'], 'checked box');
            this.productId = this.productList[i]['id'];
          }
          console.log(this.productList, 'checked box');
          this.total = 10;
          this.p = page;
          console.log(`get product list ===>`, this.productList);
        }, error => this.errorMessage = <any> error
      );
    }

    public generatorGetPage(page: number) {
      const start = (page -1) * this.pageCount;
      const end   = start + this.pageCount;
      this.productService.generatePaginate(start, end, this.statusValue, this.tagsValue, this.datesValue).subscribe(
        data => {
          this.productList = data;
          for (let i = 0; i < this.productList.length; i++) {
            this.productList[i]['checked'] = false;
            console.log(this.productList[i]['checked'], 'add <--- checked attribute');
            this.productId = this.productList[i]['id'];
          }
          console.log(this.productList, 'checked box attribute.');
          this.total = 10;
          this.p = page;
          console.log(`get product list --->`, this.productList);
        }, error => { this.errorMessage = <any> error}
      );
    }

    public generatorGetPaginate(page: number) {
      const start = (page - 1) * this.pageCount;
      const end   = start + this.pageCount;
      // this.productService
    }


    public AddProduct() {
      this.modalRef = this.bsModalService.show(
        AddProductModalDailogComponent,
        {
        animated:            true,
        keyboard:            true,
        backdrop:            true,
        ignoreBackdropClick: true
      });
    }

    public Modify() {
      this.modalRef = this.bsModalService.show(
        ModifyComponent, {
        animated:            true,
        keyboard:            true,
        backdrop:            true,
        ignoreBackdropClick: true
      });
      (<ModifyComponent>this.modalRef.content).showConfirmationModal(
        this.productList
        );
    }

    public confirmBox() {
      this.modalRef = this.bsModalService.show(
        ConfirmComponent,
        {
          animated:            true,
          keyboard:            true,
          backdrop:            true,
          ignoreBackdropClick: true
        }
      )
      this.modalRef.content.confirm.subscribe(this.deleteProduct())
    }


    public deleteProduct() {
      let productId: any[] = [];
      for (let i = 0; this.productList.length; i ++) {
        if (this.productList[i]['checked']) {
          productId.push(this.productList[i].asin);
        }
      }
      this.productService.simpleDeleteProduct(productId)
          .subscribe(
            success => {
                this.getPagePro(1);
            }
          )
    }

    public onAllChecked( isChecked:boolean) {
      this.productList.forEach( (item) => {
         item.checked = isChecked;
      });

    }

    public onRowChecked($event, itemIdx) {
      this.productList.forEach( (item, index) => {
          if ( index == itemIdx ) {
            item.checked = !item.checked;
          }
      });
    }

    public sortedField(field: any, order?:any) {
      console.log(field, order, '<---sort field--->');
      this.sortField = field;
      this.order = 'asc' ? 'asc' : 'desc';
      this.generatorGetPage(1)
    }

    public statusEvents(status: any) {
      console.log(status, '<--- status value');
      this.statusValue = status;
      // this.getPagePro(1);
      this.generatorGetPage(1);
    }


    public tagsEvent(tags: any) {
      console.log(tags, '<--- tags value');
      this.tagsValue = tags;
      this.getPagePro(1);
    }

    public datesEvent(date: any) {
      console.log(date, '<--- date value');
      this.datesValue = date;
      this.getPagePro(1)
    }


}
